from flask import Blueprint,request,render_template,jsonify,make_response,session,redirect
from model.task.ck import Cookievalue
from model import db,User
import json
import re
lg=Blueprint('login',__name__)
@lg.route('/login',methods=['GET', 'POST'])
def login():
    if request.method=='GET':
        return render_template('login.html')
    elif request.method=='POST':
        data=request.get_json()
        try:
            username=data['username']
            password=data['password']
        except KeyError:
            return jsonify({'code':400,'msg':'参数错误'})
        userres=True
        passwordres=re.match(r'[0-9a-zA-Z]{10,20}',password)
        if not (userres and passwordres):
            return jsonify(code=400,message='用户名或密码格式错误,密码和用户都为英文，数字组成，且密码10到20位，用户名2-7位')
        user=User.query.filter_by(username=username).first()
        if user is None:
            return jsonify(code=400,message='用户名不存在')
        if user.password!=password:
            return jsonify(code=400,message='密码错误')
        response=make_response(jsonify(code=200,message='登录成功',role=user.role))
        cookieObject=Cookievalue(username=username,role=user.role)
        data=json.loads(cookieObject.cookie.json())
        session['data']=data
        response.set_cookie('sign',data['sign'])
        return response
        
@lg.route('/logout',methods=['GET'])
def loginout():
    session.clear()
    response=make_response(jsonify(code=200,message='退出登录成功'))
    response.delete_cookie('sign')
    return response